package com.spring.security.email.filter;

import com.spring.security.email.config.EmailPasswordAuthenticationToken;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author HouKunLin
 */
public class EmailPasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private final static String METHOD = "POST";

    public EmailPasswordAuthenticationFilter() {
        super(new AntPathRequestMatcher("/login/email", METHOD));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        if (!METHOD.equals(request.getMethod())) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        String email = request.getParameter("email");
        String password = request.getParameter("password");

        if (email == null) {
            email = "";
        }

        if (password == null) {
            password = "";
        }

        email = email.trim();

        EmailPasswordAuthenticationToken authRequest = new EmailPasswordAuthenticationToken(email, password);

        // Allow subclasses to set the "details" property
        // 允许子类设置“details”属性
        // Provided so that subclasses may configure what is put into the authentication request's details property.
        // 提供以便子类可以配置放入身份验证请求的详细信息属性的内容。
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));

        return this.getAuthenticationManager().authenticate(authRequest);
    }
}
